package com.kedacom.freedomLabel.view.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.databinding.ViewDataBinding;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.kedacom.freedomLabel.AppExecutors;
import com.kedacom.freedomLabel.BR;
import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.base.BaseActivity;
import com.kedacom.freedomLabel.databinding.ActivityDataAnalysisBinding;
import com.kedacom.freedomLabel.databinding.ItemScaleRecordRategroyBinding;
import com.kedacom.freedomLabel.initdata.InitAll;
import com.kedacom.freedomLabel.initdata.bean.EventBusMessage;
import com.kedacom.freedomLabel.initdata.bean.RubbishBean;
import com.kedacom.freedomLabel.viewmodel.DataAnalysisViewModel;
import com.kedacom.lego.adapter.recyclerview.LegoBaseRecyclerViewAdapter;
import com.kedacom.lego.annotation.ContentView;
import com.kedacom.lego.annotation.OnMessage;
import com.kedacom.lego.annotation.ViewModel;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;


@ContentView(R.layout.activity_data_analysis)
@ViewModel(DataAnalysisViewModel.class)
public class DataAnalysisActivity extends BaseActivity<ActivityDataAnalysisBinding, DataAnalysisViewModel>
        implements
        CalendarView.OnCalendarSelectListener,
        CalendarView.OnYearChangeListener {
    private int mYear;
    CalendarLayout mCalendarLayout;
    LegoBaseRecyclerViewAdapter<RubbishBean> adapter;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

    Dialog dialog;
    private String showTime;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding.tvMonthDay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mCalendarLayout.isExpand()) {
                    mCalendarLayout.expand();
                    return;
                }
                mBinding.calendarView.showYearSelectLayout(mYear);
                mBinding.tvLunar.setVisibility(View.GONE);
                mBinding.tvYear.setVisibility(View.GONE);
                mBinding.tvMonthDay.setText(String.valueOf(mYear));
            }
        });
        findViewById(R.id.fl_current).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBinding.calendarView.scrollToCurrent();
            }
        });
        mCalendarLayout = findViewById(R.id.calendarLayout);
        mBinding.calendarView.setOnCalendarSelectListener(this);
        mBinding.calendarView.setOnYearChangeListener(this);
        mBinding.tvYear.setText(String.valueOf(mBinding.calendarView.getCurYear()));
        mYear = mBinding.calendarView.getCurYear();
        mBinding.tvMonthDay.setText(mBinding.calendarView.getCurMonth() + "月" + mBinding.calendarView.getCurDay() + "日");
        mBinding.tvLunar.setText("今日");
        mBinding.tvCurrentDay.setText(String.valueOf(mBinding.calendarView.getCurDay()));
        showTime = mBinding.calendarView.getCurYear() + "-" + mBinding.calendarView.getCurMonth() + "-" + mBinding.calendarView.getCurDay();
        mBinding.showSelect.setText(showTime + " 数据列表");

        mViewModel.getOneDate(InitAll.convert2long(showTime + " " + "00:00:00"), InitAll.convert2long(showTime + " " + "23:59:59"));

        mBinding.analyseDate.setLayoutManager(new LinearLayoutManager(this));
        adapter = new LegoBaseRecyclerViewAdapter<RubbishBean>(R.layout.item_scale_record_rategroy, new ArrayList<>(), BR.rubbish) {
            @Override
            protected void onCustomBindItem(ViewDataBinding binding, int position) {
                super.onCustomBindItem(binding, position);
                ((ItemScaleRecordRategroyBinding) binding).createTime.setText(sdf.format(new Date(adapter.getData().get(position).getWeighingTime())));
                ((ItemScaleRecordRategroyBinding) binding).index.setText(String.valueOf(position + 1));
                ((ItemScaleRecordRategroyBinding) binding).layout.setBackgroundColor(
                        ContextCompat.getColor(DataAnalysisActivity.this, position % 2 == 0 ? R.color.white_back : android.R.color.transparent)
                );

                ((ItemScaleRecordRategroyBinding) binding).createImage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mMisc.beep();
                        RubbishBean rubbishBean = adapter.getData().get(position);
                        createImage(rubbishBean);
                    }
                });

                ((ItemScaleRecordRategroyBinding) binding).deleteOne.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mMisc.beep();
                        DialogRestartApp(true, "这个时间" + sdf.format(adapter.getData().get(position).weighingTime), adapter.getData().get(position));

                    }
                });


            }
        };
        mBinding.analyseDate.setAdapter(adapter);


    }

    private void createImage(RubbishBean rubbishBean) {

        String baseUrl = PreferenceManager.getDefaultSharedPreferences(this).getString("scales_post_url_post", "");

        AppExecutors.getInstance().queryIO()
                .submit(() -> {
                    String imageUrl = baseUrl + rubbishBean.toString();
                    Bitmap bitmap = QRCodeEncoder.syncEncodeQRCode(imageUrl, BGAQRCodeUtil.dp2px(DataAnalysisActivity.this, 200));
                    mViewModel.sendMessage("BitmapShow",bitmap);

                });

    }

    @Override
    public void onCalendarOutOfRange(Calendar calendar) {

    }

    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {
        mMisc.beep();
        showTime = calendar.getYear() + "-" + calendar.getMonth() + "-" + calendar.getDay();
        mViewModel.getOneDate(InitAll.convert2long(showTime + " " + "00:00:00"), InitAll.convert2long(showTime + " " + "23:59:59"));
        mBinding.showSelect.setText(showTime + " 数据列表");

    }

    @Override
    public void onYearChange(int year) {

    }
    @OnMessage("BitmapShow")
    public void showImage(Bitmap bitmap) {

        View view = getLayoutInflater().inflate(R.layout.activity_show_zxing, null);
        final ImageView showImage = view.findViewById(R.id.show_image_zxing);

        Button dialog_cancel = view.findViewById(R.id.dialog_cancel);
        dialog = new Dialog(this, R.style.Theme_AppCompat_DayNight_DarkActionBar);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = dialog.getWindow();
        WindowManager.LayoutParams wl = window.getAttributes();
        window.setGravity(Gravity.CENTER_VERTICAL);
        int width = getWindowManager().getDefaultDisplay().getWidth();
        wl.width = (width / 3) * 1; // 宽度
        wl.height = getWindowManager().getDefaultDisplay().getHeight() * 4/ 5; // 高度
        wl.alpha = 1f; // 透明度
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.onWindowAttributesChanged(wl);
//        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        backgroundAlpha(0.3f);
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                showImage.setImageBitmap(bitmap);
            }
        });
        dialog_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                backgroundAlpha(1f);
            }
        });

        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                switch (i) {
                    case KeyEvent.KEYCODE_BACK:
                        dialog.dismiss();
                        backgroundAlpha(1f);
                        break;
                }
                return false;
            }
        });

    }


    public void onFinish(View view) {
        mMisc.beep();
        finish();
    }


    public void onDeleteOneDay(View view) {
        mMisc.beep();
        DialogRestartApp(false, showTime, null);
    }

    public void DialogRestartApp(boolean isOne, String showName, RubbishBean rubbishBean) {
        AlertDialog normalDialog =
                new AlertDialog.Builder(DataAnalysisActivity.this)
                        .setTitle("删除操作:")
                        .setMessage("要删除" + showName + "的数据吗？")
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mMisc.beep();
                                        if (isOne) {
                                            mViewModel.deleteOne(rubbishBean);
                                        } else {
                                            try {
                                                mViewModel.deleteOneDate(InitAll.convert2long(showTime + " " + "00:00:00"), InitAll.convert2long(showTime + " " + "23:59:59"));
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }

                                    }
                                })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mMisc.beep();
                            }
                        }).create();
        normalDialog.setCanceledOnTouchOutside(false);
        normalDialog.setCancelable(false);
        normalDialog.show();

    }


    @OnMessage(value = Options.MSG_POST_SUCCESS, always = true)
    public void showPostSuccess(EventBusMessage msg) {
        closeDialog();
        showToast(msg.getDes());
        if (msg.getType() == 6 || msg.getType() == 7) {
            mViewModel.getOneDate(InitAll.convert2long(showTime + " " + "00:00:00"), InitAll.convert2long(showTime + " " + "23:59:59"));
        }
    }

    /**
     * 设置背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }


    @OnMessage("getBusinessSuccess")
    private void getBusinessSuccess(List<RubbishBean> rubbishBeanList) {

        adapter.setData(rubbishBeanList);

        mBinding.showCount.setText(String.format("%s%s", "总计：", String.valueOf(rubbishBeanList.size())));
        float weight = 0;
        long number = 0;
        for (int i = 0; i < rubbishBeanList.size(); i++) {
            weight += Float.parseFloat(rubbishBeanList.get(i).weight);
        }
        mBinding.showWeight.setText(String.format("%s%s", "重量：", String.format(Locale.getDefault(), "%.2f", weight)));

        if (rubbishBeanList.size() == 0) {
            mBinding.deleteOneDay.setVisibility(View.GONE);
        } else {
            mBinding.deleteOneDay.setVisibility(View.VISIBLE);
        }

    }


}
